package com.spring.controller;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.spring.dataobject.Employee;
import com.spring.dataobject.LeaveBill;
import com.spring.form.WorkflowForm;
import com.spring.service.LeaveBillService;
import com.spring.service.WorkflowService;
import com.spring.utils.FileUtils;

/**
 * 创建时间：2018年6月22日 上午10:19:50 项目名称：activiti-spring
 * 
 * @author Mo Xiaobao
 * @version 1.0
 * @since JDK 1.8 文件名称：EmployeeController.java 类说明：
 */
@Controller
@RequestMapping("/workflow/deploye")
public class WorkflowController {

	@Autowired
	private WorkflowService workflowService;

	@Autowired
	private LeaveBillService  leaveBillService;

	/**
	 * 	部署流程定义
	 * Title: newdeploye
	 * Description:
	 * @param @param request
	 * @param @param files
	 * @param @param filename 
	 * @return void
	 */
	@PostMapping("/upload")
	public ModelAndView newdeploy(HttpServletRequest request, @RequestParam("file") MultipartFile files,
			@RequestParam("filename") String filename) {
		try {
			String path = request.getSession().getServletContext().getRealPath("/upload/");
			String suffix = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
			String fileName = UUID.randomUUID().toString() + suffix;
			File f = File.createTempFile(path, fileName);
			files.transferTo(f);
			workflowService.saveNewDeploye(f, filename);
			FileUtils.deleteFile(f);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/workflow/deploye/deployHome");
	}

	/**
	 * 部署管理首页显示
	 * Title: deployHome
	 * Description:
	 * @param @param map
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/deployHome")
	public ModelAndView deployHome(Map<String, Object> map){
		//1:查询部署对象信息，对应表(act_re_deployment)
		List<Deployment> depList = workflowService.findDeploymentList();
		//2:查询流程定义的信息，对应表(act_re_procdef)
		List<ProcessDefinition> pdList = workflowService.findProcessDefinitionList();
		
		map.put("depList", depList);
		map.put("pdList", pdList);
		return new ModelAndView("/workflow/index",map);
		}
	
	
	/**
	 * 删除部署信息
	 * Title: delDeployment
	 * Description:
	 * @param @param deploymentId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/delete")
	public ModelAndView delDeployment(@RequestParam("deploymentId") String deploymentId){
		
		workflowService.deleteProcessDefinitionByDeploymentId(deploymentId);
		return new ModelAndView("redirect:/workflow/deploye/deployHome");
	}
	
	/**
	 * 初始化流程图
	 * Title: viewInit
	 * Description:
	 * @param @param deploymentId
	 * @param @param imageName
	 * @param @param map
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/vinit")
	public  ModelAndView viewInit(@RequestParam("deploymentId") String deploymentId,
							 @RequestParam("imageName") String imageName,
						Map<String , Object> map){
		map.put("deploymentId", deploymentId);
		map.put("imageName", imageName);
		return new ModelAndView("/workflow/view",map);
	}
	
	/**
	 * 查看流程图
	 * Title: viewImage
	 * Description:
	 * @param @return 
	 * @return String
	 * @throws Exception 
	 */
	@RequestMapping("/view")
	public  String viewImage(@RequestParam("deploymentId") String deploymentId,
							 @RequestParam("imageName") String imageName,
							HttpServletResponse response) throws Exception{
		//获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
		InputStream inputStream  = workflowService.findImageInputStream(deploymentId,imageName);
		response.setHeader("Content-Type","image/jped");//设置响应的媒体类型，这样浏览器会识别出响应的是图片
		for(int b=-1;(b=inputStream.read())!=-1;){
			response.getOutputStream().write(b);
		}
		response.flushBuffer();
		inputStream.close();
		return null;
	}
	
	/**
	 * 启动流程
	 * Title: startProcess
	 * Description:
	 * @param @param id
	 * @param @param request
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("start")
	public ModelAndView startProcess(@RequestParam("id") Long id,HttpServletRequest request){
		HttpSession session = request.getSession();  
		Employee employee =(Employee) session.getAttribute("employee");
		String username = employee.getName();
		//更新请假状态，启动流程实例，让启动的流程实例关联业务
		workflowService.startProcess(id,username);
		return new ModelAndView("redirect:/workflow/deploye/listTask");
	}
	
	/**
	 * 任务管理首页显示
	 * Title: listTask
	 * Description:
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/listTask")
	public ModelAndView listTask(HttpServletRequest request,Map<String,Object> map){
		HttpSession session = request.getSession();  
		Employee employee =(Employee) session.getAttribute("employee");
		List<Task> tasks = workflowService.findTaskListByName(employee.getName());
		map.put("tasks", tasks);
		return new ModelAndView("/workflow/task",map);
	}
	
	/**
	 * 打开任务表单
	 * Title: viewTaskForm
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewTaskForm")
	public ModelAndView viewTaskForm(@RequestParam("taskId") String taskId){
		String url = workflowService.findTaskFormKeyByTaskId(taskId);
		url +="?taskId="+taskId;
		return new ModelAndView("redirect:"+url);
	}
	
	
	/**
	 * 准备表单数据
	 * Title: audit
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/audit")
	public ModelAndView audit(@RequestParam("taskId")String taskId,
							  Map<String, Object> map){
		/**一：使用任务ID，查找请假单ID，从而获取请假单信息*/
		LeaveBill leaveBill = workflowService.findLeaveBillByTaskId(taskId);
		map.put("leaveBill", leaveBill);
		map.put("taskId", taskId);
		/**二：已知任务ID，查询ProcessDefinitionEntiy对象，从而获取当前任务完成之后的连线名称，并放置到List<String>集合中*/
		List<String> outcomeList = workflowService.findOutComeListByTaskId(taskId);
		map.put("outcomeList", outcomeList);
		/**三：查询所有历史审核人的审核信息，帮助当前人完成审核，返回List<Comment>*/
		List<Comment> commentList = workflowService.findCommentByTaskId(taskId);
		map.put("commentList", commentList);
		return new ModelAndView("/workflow/taskForm",map);
		}
	
	/**
	 * 提交任务
	 * Title: submitTask
	 * Description:
	 * @param @param workflowForm
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/submitTask")
	public ModelAndView submitTask(WorkflowForm workflowForm,HttpServletRequest request){
		HttpSession session = request.getSession();  
		Employee employee =(Employee) session.getAttribute("employee");
		String username = employee.getName();
		workflowService.saveSubmitTask(workflowForm,username);
		return new ModelAndView("redirect:/workflow/deploye/listTask");
	}
	
	
	
	/**
	 * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
	 * Title: viewCurrentImage
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewCurrentImage")
	public ModelAndView viewCurrentImage(@RequestParam("taskId")String taskId,
										 Map<String, Object> map){
		/**一：查看流程图*/
		//1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
		ProcessDefinition pDefinition  = workflowService.findProcessDefinitionByTaskId(taskId);
		map.put("deploymentId", pDefinition.getDeploymentId());
		map.put("imageName", pDefinition.getDiagramResourceName());
		/**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
		Map<String, Object> acsmap = workflowService.findCoordingByTask(taskId);
		map.put("acs", acsmap);
		return new ModelAndView("/workflow/currentImage",map);
	}
	
	/**
	 * 查看历史的批注信息
	 * Title: viewHisComment
	 * Description:
	 * @param @param billId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewHisComment")
	public ModelAndView viewHisComment(@RequestParam("billId")Long billId,
										Map<String, Object> map){
		
		//1：使用请假单ID，查询请假单对象
		LeaveBill leaveBill = leaveBillService.findLeaveBillById(billId);
		map.put("leaveBill", leaveBill);
		//2：使用请假单ID，查询历史的批注信息
		List<Comment> commentList = workflowService.findCommentByLeaveBillId(billId);
		map.put("commentList", commentList);
		return new ModelAndView("/workflow/taskFormHis",map);
	}
}
